package org.changs.nav.ui.nav;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.services.help.Tip;
import com.jakewharton.rxbinding2.widget.RxTextView;

import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.nav.R;
import org.changs.nav.databinding.MainSearchPoiSearchingLayoutBinding;
import org.changs.nav.databinding.SearchRecodeItemBinding;
import org.changs.nav.databinding.SearchTipItemBinding;
import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.AmapRouteHelper;
import org.changs.nav.delegate.amap.AmapSearchHelper;
import org.changs.nav.delegate.amap.AmapTipHelper;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import aplug.data.db.SearchRecordHelper;
import aplug.data.db.mode.SearchRecord;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 惠安 on 2017/11/23.
 */

public class SearchingFragment extends BaseMapFragment {

    private static final String TAG_TYPE = "TAG_TYPE";

    public static SearchingFragment newInstance() {
        return new SearchingFragment();
    }

    private MainSearchPoiSearchingLayoutBinding mBinding;
    private SearchRecordAdapter mSearchRecordAdapter;
    private TipAdapter mTipAdapter;

    @Inject SearchRecordHelper mSearchRecordHelper;
    @Inject AmapTipHelper mAmapTipHelper;
    @Inject AmapSearchHelper mAmapSearchHelper;
    @Inject AmapRouteHelper mAmapRouteHelper;
    @Inject MapSwitchDelegate mMapSwitchDelegate;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.main_search_poi_searching_layout, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mBinding.btnSearchClear.setOnClickListener(v -> mBinding.etSearch.setText(""));
        mBinding.btnSearch.setOnClickListener(v -> {
            String keyword = mBinding.etSearch.getText().toString();
            mAmapSearchHelper.search(this, keyword, false);
            mSearchRecordHelper.insert(SearchRecord.normal(keyword))
                    .subscribeOn(Schedulers.io())
                    .subscribe();
        });

        RxTextView.textChanges(mBinding.etSearch).
                subscribe(text -> {
                    boolean hasText = text.length() > 0;
                    mBinding.btnSearch.setEnabled(hasText);
                    mBinding.btnSearchClear.setVisibility(hasText ? View.VISIBLE : View.GONE);
                    if (!hasText) setupSearchRecordList();
                });
        //搜索的提示，防拉动
        RxTextView.textChanges(mBinding.etSearch)
                .debounce(800, TimeUnit.MILLISECONDS)
                .filter(charSequence -> charSequence.length() > 0)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(text -> tip(text.toString()));
    }

    private void tip(String text) {
        mAmapTipHelper.query(text, tips -> {
            if (mTipAdapter == null) {
                mTipAdapter = new TipAdapter();
                mBinding.rccSearchTip.setLayoutManager(new LinearLayoutManager(getContext()));
                mBinding.rccSearchTip.setIAdapter(mTipAdapter);
            } else {
                mTipAdapter.getData().clear();
            }
            mBinding.rccSearchRecord.setVisibility(View.GONE);
            mBinding.rccSearchTip.setVisibility(View.VISIBLE);
            mTipAdapter.getData().addAll(tips);
            mTipAdapter.notifyDataSetChanged();
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mAmapTipHelper.stop();
    }

    private void setupSearchRecordList() {
        if (mBinding.etSearch.getText().length() != 0) return;

        if (mSearchRecordAdapter == null) {
            mSearchRecordAdapter = new SearchRecordAdapter();
            mSearchRecordAdapter.setOnItemClickListener((view, position) -> {
                SearchRecord searchRecord = mSearchRecordAdapter.getData().get(position);
                if (searchRecord.getType() == SearchRecord.TYPE_NORMAL) {
                    mAmapSearchHelper.search(this, searchRecord.getName(), false);
                } else {
                    mAmapRouteHelper.calculate(this, searchRecord.getName(), searchRecord.getAddress(),
                            searchRecord.getLatitude(), searchRecord.getLongitude());
                }
            });
            mBinding.rccSearchRecord.setLayoutManager(new LinearLayoutManager(getContext()));
            mBinding.rccSearchRecord.setIAdapter(mSearchRecordAdapter);
            View footView = LayoutInflater.from(getContext()).inflate(R.layout.search_recode_foot,
                    mBinding.rccSearchRecord, false);
            mBinding.rccSearchRecord.addFooterView(footView);
            footView.setOnClickListener(v ->
                    mSearchRecordHelper.clear()
                            .subscribeOn(Schedulers.io())
                            .subscribe());
        } else {
            mSearchRecordAdapter.getData().clear();
            mSearchRecordAdapter.notifyDataSetChanged();
        }
        mSearchRecordHelper.findAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(searchRecords -> {
                    mSearchRecordAdapter.getData().addAll(searchRecords);
                    mSearchRecordAdapter.notifyDataSetChanged();
                });
    }


    private class TipAdapter extends SimpleAdapter<Tip, SearchTipItemBinding> {
        public TipAdapter() {
            super(R.layout.search_tip_item);
            setOnItemClickListener((view, position) -> {
                Tip tip = getData().get(position);
                if (tip.getPoint() == null) {
                    mAmapSearchHelper.search(SearchingFragment.this, tip.getName(), false);
                    mSearchRecordHelper.insert(SearchRecord.normal(tip.getName()))
                            .subscribeOn(Schedulers.io())
                            .subscribe();
                } else {
                    mAmapRouteHelper.calculate(SearchingFragment.this, tip.getName(), tip.getAddress(),
                            tip.getPoint().getLatitude(), tip.getPoint().getLongitude());
                    mSearchRecordHelper.insert(SearchRecord.poi(tip.getName(), tip.getAddress(),
                            0L, tip.getPoint().getLatitude(), tip.getPoint().getLongitude()))
                            .subscribeOn(Schedulers.io())
                            .subscribe();
                }
            });
        }

        @Override
        protected void onBindViewHolder(SearchTipItemBinding binding, Tip tip, int position) {
            super.onBindViewHolder(binding, tip, position);
            final String name = tip.getName();
            binding.tvAddress.setText(tip.getDistrict());
            final String currentKey = mBinding.etSearch.getText().toString();
            final int keyIndex = name.indexOf(currentKey);
            if (keyIndex == -1) {
                binding.tvName.setTextColor(getResources().getColor(R.color.blue_black_dark));
                binding.tvName.setText(name);
            } else {
                SpannableString spannableString = new SpannableString(name);
                if (keyIndex != 0) {
                    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue_black_dark)), 0, keyIndex, 0);
                }
                int keyIndexE = keyIndex + currentKey.length();
                if (keyIndexE != name.length() - 1) {
                    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue_black_dark)), keyIndex + 1, name.length(), 0);
                }
                spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), keyIndex, keyIndexE, 0);
                binding.tvName.setText(spannableString);
            }
        }
    }


    public static class SearchRecordAdapter extends SimpleAdapter<SearchRecord, SearchRecodeItemBinding> {
        public SearchRecordAdapter() {
            super(R.layout.search_recode_item);
        }

        @Override
        protected void onBindViewHolder(SearchRecodeItemBinding binding, SearchRecord searchRecord, int position) {
            super.onBindViewHolder(binding, searchRecord, position);
            final boolean isNormal = searchRecord.getType() == SearchRecord.TYPE_NORMAL;
            binding.tvAddress.setVisibility(isNormal ? View.GONE : View.VISIBLE);
            binding.tvName.setText(searchRecord.getName());
            if (!isNormal) {
                binding.tvAddress.setText(searchRecord.getAddress());
            }
        }
    }


}
